﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;

namespace GenUI.WPF.GenControls
{
    internal class TxtPage : Control
    {
        public Pager<string> Pager { get; set; }
        private PagerBar PagerBar;
        private ListView LV;

        public IEnumerable<string> Source
        {
            get { return (IEnumerable<string>)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(IEnumerable<string>), typeof(TxtPage), new PropertyMetadata(null, OnSourceChanged));

        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is TxtPage TP && TP.LV != null && e.NewValue != null)
            {
                TP.Refresh(TP, (IEnumerable<string>)e.NewValue);
            }
        }
        static TxtPage()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(TxtPage), new FrameworkPropertyMetadata(typeof(TxtPage)));
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.PagerBar = GetTemplateChild("PART_PB") as PagerBar;
            this.LV = GetTemplateChild("PART_LV") as ListView;
            Refresh(this, Source);
        }

        private void Refresh(TxtPage Tp, IEnumerable<string> source)
        {
            Tp.Pager = new Pager<string>(8, source);
            Tp.Pager.PagerUpdated += items =>
            {
                Tp.LV.ItemsSource = items;
            };
            Tp.Pager.CurPageIndex = 1;
            Tp.PagerBar.DataContext = Tp.Pager;
        }
    }
}
